#!/bin/bash

# 接单平台状态检查脚本

# 设置变量
APP_NAME="order-platform"
PID_FILE="${APP_NAME}.pid"
LOG_FILE="logs/${APP_NAME}.log"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 检查应用状态
check_app_status() {
    if [ ! -f "$PID_FILE" ]; then
        print_message $RED "状态: 未运行"
        return 1
    fi
    
    PID=$(cat $PID_FILE)
    
    if ps -p $PID > /dev/null 2>&1; then
        print_message $GREEN "状态: 运行中"
        print_message $BLUE "PID: $PID"
        
        # 获取进程信息
        local start_time=$(ps -o lstart= -p $PID 2>/dev/null | xargs)
        local cpu_usage=$(ps -o %cpu= -p $PID 2>/dev/null | xargs)
        local mem_usage=$(ps -o %mem= -p $PID 2>/dev/null | xargs)
        local rss=$(ps -o rss= -p $PID 2>/dev/null | xargs)
        
        if [ -n "$start_time" ]; then
            print_message $BLUE "启动时间: $start_time"
        fi
        if [ -n "$cpu_usage" ]; then
            print_message $BLUE "CPU使用率: ${cpu_usage}%"
        fi
        if [ -n "$mem_usage" ]; then
            print_message $BLUE "内存使用率: ${mem_usage}%"
        fi
        if [ -n "$rss" ]; then
            local mem_mb=$((rss / 1024))
            print_message $BLUE "内存使用量: ${mem_mb}MB"
        fi
        
        return 0
    else
        print_message $RED "状态: 进程不存在"
        print_message $YELLOW "PID文件存在但进程已停止，建议清理: rm $PID_FILE"
        return 1
    fi
}

# 检查端口状态
check_port_status() {
    local port=8080
    if netstat -tlnp 2>/dev/null | grep ":$port " > /dev/null; then
        local pid_info=$(netstat -tlnp 2>/dev/null | grep ":$port " | awk '{print $7}' | head -1)
        print_message $GREEN "端口 $port: 已监听"
        if [ -n "$pid_info" ]; then
            print_message $BLUE "监听进程: $pid_info"
        fi
    else
        print_message $RED "端口 $port: 未监听"
    fi
}

# 检查日志文件
check_log_status() {
    if [ -f "$LOG_FILE" ]; then
        local log_size=$(du -h "$LOG_FILE" 2>/dev/null | cut -f1)
        local log_lines=$(wc -l < "$LOG_FILE" 2>/dev/null)
        print_message $GREEN "日志文件: 存在"
        print_message $BLUE "文件大小: $log_size"
        print_message $BLUE "行数: $log_lines"
        
        # 显示最后几行日志
        print_message $YELLOW "\n最近日志 (最后5行):"
        tail -5 "$LOG_FILE" 2>/dev/null | while read line; do
            echo "  $line"
        done
    else
        print_message $RED "日志文件: 不存在"
    fi
}

# 检查健康状态
check_health_status() {
    local health_url="http://localhost:8080/actuator/health"
    
    if command -v curl &> /dev/null; then
        local response=$(curl -s -w "%{http_code}" -o /dev/null "$health_url" 2>/dev/null)
        if [ "$response" = "200" ]; then
            print_message $GREEN "健康检查: 正常"
            
            # 获取详细健康信息
            local health_info=$(curl -s "$health_url" 2>/dev/null)
            if [ -n "$health_info" ]; then
                echo "健康详情: $health_info"
            fi
        else
            print_message $RED "健康检查: 异常 (HTTP $response)"
        fi
    else
        print_message $YELLOW "健康检查: 跳过 (未安装curl)"
    fi
}

# 显示系统资源
show_system_resources() {
    print_message $BLUE "\n系统资源:"
    
    # CPU信息
    if command -v nproc &> /dev/null; then
        local cpu_cores=$(nproc)
        print_message $BLUE "CPU核心数: $cpu_cores"
    fi
    
    # 内存信息
    if [ -f /proc/meminfo ]; then
        local total_mem=$(grep MemTotal /proc/meminfo | awk '{print int($2/1024)}')
        local free_mem=$(grep MemAvailable /proc/meminfo | awk '{print int($2/1024)}')
        local used_mem=$((total_mem - free_mem))
        print_message $BLUE "内存: ${used_mem}MB / ${total_mem}MB"
    fi
    
    # 磁盘信息
    if command -v df &> /dev/null; then
        local disk_usage=$(df -h . | tail -1 | awk '{print $3 "/" $2 " (" $5 ")"}')
        print_message $BLUE "磁盘使用: $disk_usage"
    fi
    
    # 负载信息
    if [ -f /proc/loadavg ]; then
        local load_avg=$(cat /proc/loadavg | awk '{print $1 ", " $2 ", " $3}')
        print_message $BLUE "系统负载: $load_avg"
    fi
}

# 显示帮助信息
show_help() {
    echo "接单平台状态检查脚本"
    echo ""
    echo "使用方法:"
    echo "  $0 [选项]"
    echo ""
    echo "选项:"
    echo "  -h, --help     显示帮助信息"
    echo "  -l, --log      显示更多日志信息"
    echo "  -s, --simple   简单模式，只显示基本状态"
    echo ""
    echo "示例:"
    echo "  $0             # 显示完整状态信息"
    echo "  $0 -s          # 显示简单状态信息"
    echo "  $0 -l          # 显示状态和更多日志"
}

# 主函数
main() {
    local show_log=false
    local simple_mode=false
    
    # 解析参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                show_help
                exit 0
                ;;
            -l|--log)
                show_log=true
                shift
                ;;
            -s|--simple)
                simple_mode=true
                shift
                ;;
            *)
                print_message $RED "未知参数: $1"
                show_help
                exit 1
                ;;
        esac
    done
    
    # 显示标题
    print_message $GREEN "=================================="
    print_message $GREEN "    接单平台状态检查 v1.0"
    print_message $GREEN "=================================="
    
    # 检查应用状态
    print_message $YELLOW "\n应用状态:"
    check_app_status
    local app_running=$?
    
    if [ "$simple_mode" = false ]; then
        # 检查端口状态
        print_message $YELLOW "\n网络状态:"
        check_port_status
        
        # 检查健康状态
        if [ $app_running -eq 0 ]; then
            print_message $YELLOW "\n健康状态:"
            check_health_status
        fi
        
        # 显示系统资源
        show_system_resources
    fi
    
    # 检查日志状态
    print_message $YELLOW "\n日志状态:"
    check_log_status
    
    # 显示更多日志
    if [ "$show_log" = true ] && [ -f "$LOG_FILE" ]; then
        print_message $YELLOW "\n详细日志 (最后20行):"
        tail -20 "$LOG_FILE" 2>/dev/null | while read line; do
            echo "  $line"
        done
    fi
    
    print_message $GREEN "\n=================================="
    
    # 返回应用状态
    exit $app_running
}

# 执行主函数
main "$@"